package com.lin.blog.service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import com.google.appengine.api.datastore.AsyncDatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public final class IDService {
	public static final long MENU_ID_FIELD_NAME = 0x0000000000000000001;
	public static final String ID_TABLE_NAME = "idtable";
	public static final String VALUE_FIELD_NAME = "value";
	private static final IDService instance = new IDService();
	private AsyncDatastoreService datastoreService = DatastoreServiceFactory
			.getAsyncDatastoreService();
	private static final Map<String, Long> map = new HashMap<String, Long>();
	static {
		map.put("Menu", MENU_ID_FIELD_NAME);
	}

	private IDService() {
	}

	public void setDatastoreService(AsyncDatastoreService datastoreService) {
		this.datastoreService = datastoreService;
	}

	public static final IDService getInstance(
			AsyncDatastoreService datastoreService) {
		instance.setDatastoreService(datastoreService);
		return instance;
	}

	public static final IDService getInstance() {
		instance.setDatastoreService(DatastoreServiceFactory
				.getAsyncDatastoreService());
		return instance;
	}

	public long getIdByType(String type) {
		return getID(map.get(type));
	}

	private void save(long id, long value) {
		Entity entity = new Entity(ID_TABLE_NAME, id);
		entity.setProperty(VALUE_FIELD_NAME, value);
		datastoreService.put(entity);
	}

	public void update(String type, long value) {
		Entity entity = new Entity(ID_TABLE_NAME, map.get(type));
		entity.setProperty(VALUE_FIELD_NAME, value);
		datastoreService.put(entity);
	}

	private long getID(long id) {
		Key key = KeyFactory.createKey(ID_TABLE_NAME, id);
		long sid = 0;
		try {
			Entity entity = datastoreService.get(key).get();
			sid = new Long(entity.getProperty(VALUE_FIELD_NAME).toString());
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		return sid;
	}

	public void init() {
		save(MENU_ID_FIELD_NAME, 1l);
	}
}
